package com.qf.homework.common;

import com.alibaba.fastjson.JSON;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Properties;

/**
 * @author zehan
 * @date 2022/8/19 11:22
 */
@WebServlet(urlPatterns ="/",loadOnStartup = 1)
public class DispatchServlet extends HttpServlet {

    private ApplicationContext context;
    private Properties ps;
    @Override
    public void init() throws ServletException {
        super.init();
        System.out.println("servlet 启动了");
        // 1 初始化spring 容器
        context = new ClassPathXmlApplicationContext("classpath:beans.xml");

        // 2 读取路径 和 controller 的映射。。。。
        ps = new Properties();
        ServletContext application =
                this.getServletContext();
        try {
            ps.load(application.getResourceAsStream("/WEB-INF/path_controller.properties"));

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //System.out.println("请求来了 请求的地址是：" + request.getServletPath());
        // 1 获得页面 上请求的路径
        String path = request.getServletPath();
        // 2 根据路径获得 路径映射的类的名字
        String className = ps.getProperty(path);
        // 3 还要获得bean 钟要执行的方法
        String methodName = request.getParameter("method");

        System.out.println("页面上请求的路劲是："+path);
        System.out.println("路径对应的类：" +className);
        System.out.println("执行类种的方法是：" +methodName);

        // 3 从spring 容器种获得 bean
        try {
            Class clazz = Class.forName(className);
            Object bean = context.getBean(clazz);
            // 执行bean 种的方法
            // 1 获得method 的 字节对象
            Method method = clazz.getDeclaredMethod(methodName,HttpServletRequest.class);
            Object invoke = method.invoke(bean, request);
            // 改变响应的格式  默认（html---> json）
            response.setContentType("text/json");
            // 改变响应的字符集合
            response.setCharacterEncoding("utf-8");
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Content-Type");
            response.setHeader("Access-Control-Allow-Credentials", "true");

            response.getWriter().write(JSON.toJSONString(invoke));
        } catch (Exception e) {
            e.printStackTrace();
        }



    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
